<?php

class Dispatcher {
	
	public static function dispatch() {
		$request = self::_loadRequest();
		$className = file2class($request["controller"]);
		
		$path = dirname(__FILE__) . "/../app/controllers/".class2file($className).".controller.php";
		if(!file_exists($path)){
			$className = "Page";
			$request["params"] = array($request["controller"]);
			$request["controller"] = $className;
			$request["action"] = "show";
		}
		$ctrl = new $className();
		$ctrl->request = (Object)$request;
		
		if(method_exists($ctrl, $request["action"])) {
			$ctrl->init();
			$params = $request["params"] ? '"' . implode('","', $request["params"]) . '"' : "";
			$toeval = '$ctrl->' . $request["action"] . "($params);";
			eval($toeval);
			if($ctrl->autoRender) {
				$ctrl->render();
			}
		}else{
			$ctrl->render("errors/missing_action");
		}
	}
	
	public static function _loadRequest($request=null) {
		$r = preg_split('/\//', $request ? $request : $_GET["request"], -1, PREG_SPLIT_NO_EMPTY);
		$named = array();		
		foreach($r as $k=>$v) {
			if(strstr($v, ";")) {
				list($name, $value) = explode(";", $v, 2);
				$named[$name] = $value;
				unset($r[$k]);
			}
		}
		$r = array_values($r);
		$controller = $r[0]=="admin" ? array_shift($r) : null;
		if($controller=="admin"){
			$action = array_shift($r);
		}else{
			$action = "show";
		}
		return array(
			"named" => $named,
			"controller" => $controller ? $controller : DEFAULT_CONTROLLER,
			"action" => $action ? $action : DEFAULT_ACTION,
			"params" => $r
		);
	}
}

?>